package cn.com.guage.lru;

import java.util.LinkedHashMap;

public class LRUCache {
	LinkedHashMap<Integer, Integer> linkedHashMap;
	int capacity;

	public LRUCache(int capacity) {
		linkedHashMap = new LinkedHashMap<Integer, Integer>(capacity);
		this.capacity = capacity;
	}

	public int get(int key) {
		if (linkedHashMap.containsKey(key)) {
			int value = linkedHashMap.get(key);
			linkedHashMap.remove(key);
			linkedHashMap.put(key, value);
			return value;
		}
		return -1;

	}

	public void put(int key, int value) {
		if (linkedHashMap.containsKey(key)) {
			linkedHashMap.remove(key);
		} else if (linkedHashMap.size() >= capacity) {

			linkedHashMap.remove(linkedHashMap.keySet().iterator().next());
		}
		linkedHashMap.put(key, value);

	}
	
	public static void main(String[] args) {
		LRUCache lRUCache = new LRUCache(2);
		lRUCache.put(1, 1); // 缓存是 {1=1}
		lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
		System.out.println(lRUCache.get(1));  // 返回 1
		lRUCache.put(3, 3); // 该操作会使得关键字 2 作废，缓存是 {1=1, 3=3}
		System.out.println(lRUCache.get(2));  // // 返回 -1 (未找到)

		lRUCache.put(4, 4); // 该操作会使得关键字 1 作废，缓存是 {4=4, 3=3}
		System.out.println(lRUCache.get(1));  // 返回 -1 (未找到)
		System.out.println(lRUCache.get(3));   // 返回 3
		System.out.println(lRUCache.get(4));   // 返回 4

	}

}